import { initTask, im_list, getIMConfig, setIMConfig} from "@/utils/config"
let loopCount = 3 

export default class Socket {
	constructor({
		protocol = 'ws://',
		IP = 'localhost',
		port = '8888',
		method='GET'
	}={}) {
		this.protocol = protocol
		this.IP = IP
		this.port = port
		this.method= method
		this.socketTask=null
		
		this.errorHandle=(e)=>{
			console.error(e)
		}
		this.messageHandle = (msg) =>{
			console.log(msg)
		}
		this.closeHandle = (e)=>{
			console.log('socket链接已关闭',e)
		}
		this.openHandle = ()=>{
			console.log('socket链接已打开')
		}
	}
	async connect(data){
		await initTask
		for (let i = 1; i <= im_list.length*loopCount; i++) {
			try{
				const config = getIMConfig()
				const url = config.protocol+config.IP+":"+config.port+(data?`?${data}`:'');
				const res = await new Promise((resolve,reject)=>{
					const socketTask = uni.connectSocket({
						url:url,
						method:config.method,
						success(){
							console.log('创建函数执行成功')
						},
						fail:(e)=>{
							reject(e)
							console.log('创建函数执行失败')
						},
						complete() {
							console.log('创建函数执行完毕')
						}
					});
					
					socketTask.onOpen((data)=>{
						console.log('socketTask.onOpen',data)
						this.openHandle(data)
						resolve(data)
						this.socketTask = socketTask
					});
					socketTask.onError((e)=>{
						console.log('socketTask.onError',e)
						this.errorHandle(e)
						reject(e)
					})
					socketTask.onClose(({code,reason})=>{
						console.log('socketTask.onClose',code,reason)
						console.log(socketTask._webSocket.url)
						this.closeHandle({code,reason})
						reject({code,reason})
					});
					socketTask.onMessage((data)=>{
						this.messageHandle(data)
					});
				})
				this.protocol = config.protocol
				this.IP = config.IP
				this.port = config.port
				this.method = config.method
				return res
			}catch(e){
				setIMConfig(im_list[i%im_list.length])
				if(i>=im_list.length*loopCount){
					throw e
				}
			}
		}
	}
	async send(data){
		if(!this.socketTask){
			throw new Error('连接尚未创建,无法发送数据')
		}
		if(typeof data == 'object'){ 
			data = JSON.stringify(data)
		}
		return new Promise((resolve,reject)=>{
			this.socketTask.send({
				data,
				success:resolve,
				fail:reject
			})
		})
	}
	async close({code=1000,reason='主动断开'}={}){
		if(!this.socketTask){
			throw new Error('连接尚未创建,无法close')
		}
		return new Promise((resolve,reject)=>{
			this.socketTask.close({
				code,
				reason,
				success:resolve,
				fail:reject
			})
		})
	}
	onError(handle){
		this.errorHandle = handle
	}
	onOpen(handle){
		this.openHandle = handle
	}
	onClose(handle){
		this.closeHandle = handle
	}
	onMessage(handle){
		this.messageHandle = handle
	}
}